import { Component, OnInit } from '@angular/core';
import {Media} from "../../model/Media";
import {MediaService} from "../../service/media.service";
import {DialogService} from "primeng/api";
import {MediaeditComponent} from "../mediaedit/mediaedit.component";

@Component({
  selector: 'app-mediaadmin',
  templateUrl: './mediaadmin.component.html',
  styleUrls: ['./mediaadmin.component.css']
})
export class MediaadminComponent implements OnInit {

  ml:Array<Media>
  constructor(private mediaservice:MediaService
    ,private dialogService: DialogService) {
    this.ml=new Array();

  }

  ngOnInit() {
    this.loadMediaList();

  }


  //从服务器端获取单页列表数据
  loadMediaList(){
    this.mediaservice.getMediaList("VIDEO")

      .then((data:any)=>{
        this.ml=new Array();
        this.ml=data;

      })


  }

  add(){
    //弹出编辑窗口
    const ref = this.dialogService.open(MediaeditComponent, {
      header: '添加视频'

    });

    //订阅窗口关闭事件

    ref.onClose.subscribe((media: Media) => {
      if (media) {
        //保存数据到服务器
        this.mediaservice.saveMedia(media)
          .then((data:any)=>{
            if(data.msg=='ok'){
              this.loadMediaList();
            }
            else{
              //提示错误
            }


          })




      }
    });



  }

  //删除

  delete(id:string){

    this.mediaservice.deleteMedia(id)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.loadMediaList();
        }
        else{
          //弹出错误信息;
        }


      })


  }

  update(id:string){
    //从服务器端读取数据
    this.mediaservice.getMediaListById(id)
      .then((data:any)=>{
        if(data){
          let media:Media;
          media=new Media();
          media=data;

          //发送要编辑的数据到编辑窗口
          //弹出编辑窗口
          const ref = this.dialogService.open(MediaeditComponent, {
            header: '修改视频',
            data:{
              "media":media
            }

          });

          //订阅窗口关闭事件

          ref.onClose.subscribe((media: Media) => {
            if (media) {
              //保存数据到服务器
              this.mediaservice.saveMedia(media)
                .then((data:any)=>{
                  if(data.msg=='ok'){
                    this.loadMediaList();
                  }
                  else{
                    //提示错误
                  }


                })




            }
          });


        }


      });




  }



}

